package com.hang.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hang.entity.Role;
import com.hang.entity.User;
import com.hang.exception.MyException;
import com.hang.exception.MyExceptionEnum;
import com.hang.mapper.UserMapper;
import com.hang.model.dto.request.RoleQueryDTO;
import com.hang.model.dto.response.RoleQueryListVO;
import com.hang.service.IRoleService;
import com.hang.mapper.RoleMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 *
 */
@Service
@AllArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
    implements IRoleService{
    private RoleMapper roleMapper;

    private UserMapper userMapper;

    /**
     * 创建角色接口
     * @param roleName
     * @param remarks
     * @return
     */
    @Override
    public boolean createRole(String roleName, String remarks) {
        if(StrUtil.isBlank(roleName)){
            throw new MyException(MyExceptionEnum.MUST_FIELD_IS_NULL);
        }

        int insert = 0;
        if(StrUtil.isBlank(remarks)){
            Role role = new Role(roleName);
            insert = roleMapper.insert(role);
        }else {
            Role role = new Role(roleName,remarks);
            insert = roleMapper.insert(role);
        }

        return insert>0?Boolean.TRUE:Boolean.FALSE;
    }

    /**
     * 修改角色
     *      - 需要将角色关联的用户信息作修改
     * @param roleId
     * @param roleName
     * @param remarks
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRole(Long roleId, String roleName, String remarks) {
        if(ObjectUtils.isEmpty(roleId)){
            throw new MyException(MyExceptionEnum.ID_IS_NULL);
        }

        Role role = roleMapper.selectById(roleId);
        String oldRoleName = role.getRoleName();

        role.setRoleName(roleName);
        role.setRemarks(remarks);

        //更新操作
        int updateRoleFlag = roleMapper.updateById(role);
        //如果角色名有更改，那么就修改用户表中的所有角色的角色名称
        if(!StrUtil.equals(oldRoleName,roleName)){
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("role_id",roleId);
            List<User> users = userMapper.selectList(userQueryWrapper);

            users.forEach(user -> {
                user.setRoleName(roleName);
                userMapper.updateById(user);
            });
        }

        return updateRoleFlag > 0?Boolean.TRUE:Boolean.FALSE;
    }

    /**
     * 根据查询条件搜索角色
     * @param roleQueryDTO
     * @return
     */
    @Override
    public RoleQueryListVO getRoleByCondition(RoleQueryDTO roleQueryDTO) {
        RoleQueryListVO roleQueryListVO = new RoleQueryListVO();

        if(ObjectUtil.isEmpty(roleQueryDTO)){
            throw new MyException(MyExceptionEnum.OBJECT_IS_NULL);
        }

        String roleName = Optional.ofNullable(roleQueryDTO.getRoleName()).orElse(null);
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        if(StrUtil.isNotBlank(roleName)){
            roleQueryWrapper.lambda().like(Role::getRoleName,roleName);
        }

        Integer pageNum = roleQueryDTO.getPageNum();
        Integer pageSize = roleQueryDTO.getPageSize();
        Page<Role> rolePage = new Page<>(pageNum,pageSize);
        IPage<Role> iPage = roleMapper.selectPage(rolePage,roleQueryWrapper);

        List<Role> roleList = iPage.getRecords();

        roleList.forEach(
                role ->{
                    if(ObjectUtil.isEmpty(role.getRemarks())){
                        role.setRemarks("");
                    }
                }
        );


        roleQueryListVO.setTotal(Optional.ofNullable(roleMapper.selectCount(roleQueryWrapper)).orElse(0));
        roleQueryListVO.setRoleList(roleList);

        return roleQueryListVO;
    }
}